﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KvoMvc.BusinessEntity;
using System.Data;

namespace KvoMvc.DataAccess
{
    public class SchoolDataAccessor
    {
        public static List<Person> GetPersonList()
        {
            var db = new SchoolContext();
            return db.Person.ToList<Person>();
        }

        public static List<Department> GetDepartmentList()
        {
            var db = new SchoolContext();
            return db.Department.ToList<Department>();
        }

        public static Person GetPersonById(int id)
        {
            var db = new SchoolContext();
            Person result = db.Person.Find(id);
            return result;
        }

        public static int CreatePerson(Person person)
        {
            int result = -1;
            try
            {
                //SchoolContext db = new SchoolContext();
                using (SchoolContext db = new SchoolContext())
                {
                    try
                    {
                        db.Person.Add(person);
                        result = db.SaveChanges();
                    }
                    catch (OptimisticConcurrencyException)
                    {
                        // Resolve the concurrency conflict by refreshing the  
                        // object context before re-saving changes. 
                        //db.re(RefreshMode.ClientWins, orders);

                        // Save changes.
                        result = db.SaveChanges();
                    }
                }
            }
            catch (UpdateException ex)
            {
                
                throw ex;
            }

            return result;
        }

        public static int UpdatePerson(Person person)
        {
            int result = -1;
            try
            {
                //SchoolContext db = new SchoolContext();
                using (SchoolContext db = new SchoolContext())
                {
                    try
                    {
                        db.Entry(person).State = EntityState.Modified;
                        result = db.SaveChanges();
                    }
                    catch (OptimisticConcurrencyException)
                    {
                        // Resolve the concurrency conflict by refreshing the  
                        // object context before re-saving changes. 
                        //db.re(RefreshMode.ClientWins, orders);

                        // Save changes.
                        result = db.SaveChanges();
                    }
                }
            }
            catch (UpdateException ex)
            {
                
                throw ex;
            }

            return result;
        }

        
    }
}
